package cn.thornbird.orgsync.vo.record;

import cn.thornbird.orgsync.util.ReflectUtil;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import javax.persistence.MappedSuperclass;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
@MappedSuperclass
public abstract class Record<T> {

    private String id;

    public void setProperties(T entity) {
        setProperties(entity, false);
    }

    public void setProperties(T entity, boolean ignoreNulls) {
        if (ignoreNulls) {
            List<String> ignoreProperties = new ArrayList<>();
            Map<String, Object> values = ReflectUtil.getValues(this);
            for (Map.Entry<String, Object> entry : values.entrySet()) {
                if (entry.getValue() == null) {
                    ignoreProperties.add(entry.getKey());
                }
            }
            BeanUtils.copyProperties(this, entity, ignoreProperties.toArray(new String[0]));
        } else {
            BeanUtils.copyProperties(this, entity);
        }
    }

    public void copyProperties(T entity) {
        BeanUtils.copyProperties(entity, this);
    }

}
